package com.smarthome.api.mobile.service;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSON;
import com.smarthome.common.mobile.Service;
import com.smarthome.core.historyAccount.HistoryAccountService;
import com.smarthome.core.historyAccount.SrcAreaDetailService;
import com.smarthome.core.housemanager.ResidenceManagerService;
import com.smarthome.core.kuaidiXiyi.SendCourierService;
import com.smarthome.core.kuaidiXiyi.XiyiOrderService;
import com.smarthome.domain.bean.ShHistoryAccount;
import com.smarthome.domain.bean.ShOrderLaundryFee;
import com.smarthome.domain.bean.ShOrders;
import com.smarthome.domain.bean.ShResidence;
import com.smarthome.domain.bean.ShSrcAreaDetail;
import com.smarthome.domain.enums.OrdersPaymentStatus;
import com.smarthome.domain.mobile.MobileCodeEnum;
import com.smarthome.domain.mobile.MobileResponse;
import com.smarthome.domain.mobile.req.MobileOrdersRequest;
import com.smarthome.domain.vo.boss.DataGrid;
import com.smarthome.domain.vo.boss.PageHelper;
/**
 * 
* @ClassName: MobileOrdersService
* @Description: 订单移动端service接口
* @author cyj
* @date 2016年3月26日 下午5:51:06
*
 */
@org.springframework.stereotype.Service("mobile.orders.service")
public class MobileOrdersService implements Service<MobileResponse<?>>{
	
	@Resource
	private SendCourierService sendCourierService;
	
	@Resource
	private ResidenceManagerService residenceManagerService;
	
	@Resource
    private XiyiOrderService xiyiOrderService;
	
	@Resource
    private HistoryAccountService historyAccountService;
	
	@Resource
	private SrcAreaDetailService srcAreaDetailService;
	
	/**
	 * 
	* @Title: addSendCourierOrder 
	* @Description: 添加快递代发订单 
	* @param request
	* @param response
	* void
	* @throws 
	* @author cyj
	 */
	public void addSendCourierOrder(MobileOrdersRequest request,MobileResponse<Long> response) {
		if(request.getAccount() == null || request.getAccountId() == null) {
			response.setMobileCodeObj(MobileCodeEnum.ORDERS_NOT_SRCACCOUNT);
			return;
		}
		if(request.getAccount().getResidenceId() == null) {
			response.setMobileCodeObj(MobileCodeEnum.ORDERS_NOT_RESIDENCE);
			return;
		}
		if(StringUtils.isBlank(request.getDesAccountName())) {
			response.setMobileCodeObj(MobileCodeEnum.ORDERS_NOT_DESACCOUNT_NAME);
			return;
		}
		if(StringUtils.isBlank(request.getDesAccountMobile())) {
			response.setMobileCodeObj(MobileCodeEnum.ORDERS_NOT_DESACCOUNT_MOBILE);
			return;
		}
		if(StringUtils.isBlank(request.getDesAccountAreaDetail())) {
			response.setMobileCodeObj(MobileCodeEnum.ORDERS_NOT_DESACCOUNT_AREA_DETAIL);
			return;
		}
		if(request.getDesAccountAreaId() == null) {
			response.setMobileCodeObj(MobileCodeEnum.ORDERS_NOT_DESACCOUNT_AREA_ID);
			return;
		}
		if(request.getAmount() == null) {
			response.setMobileCodeObj(MobileCodeEnum.ORDERS_NOT_FEE);
			return;
		}
		if(request.getWeight() == null) {
			response.setMobileCodeObj(MobileCodeEnum.ORDERS_NOT_WEIGHT);
			return;
		}
		if(StringUtils.isBlank(request.getSrcAccountAreaDetail())) {
			response.setMobileCodeObj(MobileCodeEnum.ORDERS_NOT_SRCACCOUNT_AREA_DETAIL);
			return;
		}
		
		ShResidence residence = residenceManagerService.queryResidenceById(request.getAccount().getResidenceId());
		ShOrders shOrders = new ShOrders(); 
		shOrders.setSrcAccountId(request.getAccountId());
		shOrders.setSrcAccountName(StringUtils.isBlank(request.getAccount().getName())?"客户":request.getAccount().getName());
		shOrders.setSrcAreaDetail(/*residence.getAddress() + */request.getSrcAccountAreaDetail());
		shOrders.setSrcAreaId(residence.getAreaId());
		shOrders.setSrcMobile(request.getAccount().getLoginName());
		shOrders.setAccount_id(request.getAccount().getId().toString());//订单所属的用户id
		
		ShHistoryAccount desHistoryAccount = new ShHistoryAccount();
		//desHistoryAccount.setResidenceId(request.getAccount().getResidenceId());
		desHistoryAccount.setMobile(request.getDesAccountMobile());
		desHistoryAccount.setAccountId(request.getAccountId());
		desHistoryAccount = sendCourierService.getHistoryAccountInfo(desHistoryAccount);
		if(desHistoryAccount != null && desHistoryAccount.getId() != null) {
			shOrders.setDesAccountId(desHistoryAccount.getId());
		}
		shOrders.setDesAccountName(request.getDesAccountName());
		shOrders.setDesAreaDetail(request.getDesAccountAreaDetail());
		shOrders.setDesAreaId(request.getDesAccountAreaId());
		shOrders.setDesMobile(request.getDesAccountMobile());
		
		shOrders.setCompanyId(request.getCompanyId());
		shOrders.setCourierType(1);
		Date nowDate = new Date();
		shOrders.setGmtCreate(nowDate);
		shOrders.setGmtModify(nowDate);
		shOrders.setOrderType(2);
		shOrders.setRemark(request.getRemark());
		shOrders.setResidenceId(request.getAccount().getResidenceId());
		shOrders.setName("快递代发");
		shOrders.setStatus(1);
		shOrders.setAmount(request.getAmount());
		shOrders.setWeight(request.getWeight());
		shOrders.setPaymentStatus(OrdersPaymentStatus.DEEPEND.getType());
		try {
			Integer result = sendCourierService.add(shOrders);
			if(result == 1) {
				response.setMobileCodeObj(MobileCodeEnum.COMMON_SUCCESS);
				response.setData(shOrders.getId());
			}else {
				response.setMobileCodeObj(MobileCodeEnum.ORDERS_ADD_FAIL);
			}
		}catch(Exception e) {
			e.printStackTrace();
			response.setMobileCodeObj(MobileCodeEnum.SYSTEM_ERROR);
		}
		
	}
	
	/**
	 * 
	* @Title: chengeStatus 
	* @Description: 更改状态 
	* @param request
	* @param response
	* void
	* @throws 
	* @author cyj
	 */
	public void chengeStatus(MobileOrdersRequest request,MobileResponse<?> response) {
		if(request.getId() == null) {
			response.setMobileCodeObj(MobileCodeEnum.ORDERS_ID);
			return;
		}
		if(request.getStatus() == null) {
			response.setMobileCodeObj(MobileCodeEnum.ORDERS_NOT_STATUS);
			return;
		}
		try{
			Integer result = sendCourierService.chengeStatus(request.getId(), request.getStatus());
			if(result == 1) {
				response.setMobileCodeObj(MobileCodeEnum.COMMON_SUCCESS);
			}else {
				response.setMobileCodeObj(MobileCodeEnum.ORDERS_UPDATE_FAIL);
			}
		}catch(Exception e) {
			e.printStackTrace();
			response.setMobileCodeObj(MobileCodeEnum.SYSTEM_ERROR);
		}
	}

	
	/**
	 * 洗衣服--下单
	 * @param request
	 * @param response
	 * 
	 * http://127.0.0.1:8080/mobile/gateway.do?service=mobile.orders.service&method=addWishOrder&accountId=40&residenceId=2&wishNum=2&desAccountMobile=13488901300&remark=oiuyt&loginToken=91c8b78294cfd839ad312f88fb837d8fa67225e3
	 */
	public void addWishOrder(MobileOrdersRequest request,MobileResponse<Long> response) {
		if(request.getAccount() == null || request.getAccountId() == null) {
			response.setMobileCodeObj(MobileCodeEnum.ORDERS_NOT_SRCACCOUNT);//下单人id
			return;
		}
		if(request.getAccount().getResidenceId() == null) {
			response.setMobileCodeObj(MobileCodeEnum.ORDERS_NOT_RESIDENCE);//下单人所属小区id
			return;
		}
		if(StringUtils.isBlank(request.getSrcAccountMobile())) {
			response.setMobileCodeObj(MobileCodeEnum.ORDERS_NOT_SRCACCOUNT_MOBILE);//联系电话
			return;
		}
		/*if(StringUtils.isBlank(request.getRemark())) {
			response.setMobileCodeObj(MobileCodeEnum.ORDERS_REMARK);//订单备注
			return;
		}*/
		if(request.getCompanyId()==null) {
			response.setMobileCodeObj(MobileCodeEnum.ORDERS_WISH_SHOP);//洗衣店id
			return;
		}
		try {
	    	Long residenceId = request.getAccount().getResidenceId();//用户所在小区
			ShResidence residence = residenceManagerService.queryResidenceById(residenceId);
			
			//通过手机号码查询用户是否存在
	    	ShHistoryAccount srcHistoryAccount = null;
	    	ShHistoryAccount shHistoryAccount = new ShHistoryAccount();
	    	shHistoryAccount.setMobile(request.getSrcAccountMobile());//手机号码
	    	shHistoryAccount.setResidenceId(residenceId);
	    	List<ShHistoryAccount> list = historyAccountService.queryShHistoryAccountList(shHistoryAccount);
	    	Long historyAccountId = null;
	    	if(list!=null && list.size()>0){//如果用户已存在，就修改地址
	    		srcHistoryAccount = list.get(0);//得到已近存在的历史用户
	    		srcHistoryAccount.setAreaDetail(request.getSrcAccountAreaDetail());//区域地址
	    		historyAccountService.update(srcHistoryAccount);
	    		historyAccountId = srcHistoryAccount.getId();
	    	}else{									//没有就新增
	    		shHistoryAccount.setAccountId( request.getAccount().getId());//登录人账户id
	    		shHistoryAccount.setStatus(1);				//是否可用,1可用,2不可用
	    		shHistoryAccount.setGmtCreate(new Date());	//创建时间
	    		shHistoryAccount.setAreaDetail(request.getSrcAccountAreaDetail());
	    		historyAccountService.add(shHistoryAccount);
	    		historyAccountId = shHistoryAccount.getId();
	    	}
			
			//保存订单信息
			ShOrders shOrders = new ShOrders();
			/*SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
	    	String orderNum= sdf.format(new Date());
	    	int num=(int)(Math.random()*900)+100; 
	    	int i= new java.util.Random().nextInt(900)+100;也可以
	    	shOrders.setId(Long.valueOf(orderNum+num));	*/	//订单编号
	    	shOrders.setResidenceId(residenceId);			//用户所在小区
	    	shOrders.setSrcAccountId(historyAccountId);	//发件人id，订单表的srcAccountId和desAccountId都是存的历史用户表的id
	    	shOrders.setSrcAccountName(request.getAccount().getName());
			shOrders.setSrcAreaDetail(request.getSrcAccountAreaDetail());
			shOrders.setSrcAreaId(residence.getAreaId());
			shOrders.setSrcMobile(request.getSrcAccountMobile());
			shOrders.setAccount_id(request.getAccount().getId().toString());//订单所属的用户id
	    	shOrders.setCompanyId(request.getCompanyId());
	    	shOrders.setGmtCreate(new Date());				//创建时间
	    	shOrders.setStatus(1);							//订单状态,1待处理
	    	shOrders.setOrderType(3);						//订单类型,1收快递,2发快递,3洗衣
	    	shOrders.setCourierType(request.getCourierType());//快递类型：1，普通、2，及时
	    	shOrders.setName("洗衣服务"/*+shOrders.getOutBizNum()*/);     //订单名称   先写死  洗衣服务+订单号
	    	shOrders.setRemark(request.getRemark());						//洗衣备注
	    	/*String amountStr = "2";	//费用
	    	Long amount=0l;//shOrders.getAmount();
	    	if(amountStr!=null&&StringUtils.isNotBlank(amountStr)){
	    		double amount_d = (Double.valueOf(amountStr).doubleValue())*100;//转为分
	    		amount = (long)amount_d;
	    	}
	    	shOrders.setAmount(amount);*/
	    	
	    	//cyj 扩展订单费用保存
	    	int wishNum = 0;
    		long wishTotalFee = 0;
    		List<ShOrderLaundryFee> orderLaundryFeeList = null;
    		if(StringUtils.isNotBlank(request.getOrderLaundryFeeList())) {
    			orderLaundryFeeList = JSON.parseArray(request.getOrderLaundryFeeList(), ShOrderLaundryFee.class);
    	    	if(orderLaundryFeeList != null && !orderLaundryFeeList.isEmpty()) {
    	    		int length = orderLaundryFeeList.size();
    	    		for(int i = 0;i < length;i++) {
    	    			wishNum += orderLaundryFeeList.get(i).getNum();
    	    			wishTotalFee += orderLaundryFeeList.get(i).getTotalFee();
    	    		}
    	    	}
    		}
	    	
	    	shOrders.setWishNum(wishNum);		//件数
	    	shOrders.setAmount(wishTotalFee);	//费用
	    	shOrders.setPaymentStatus(OrdersPaymentStatus.DEEPEND.getType());
	    	xiyiOrderService.add(shOrders);	//保存洗衣订单
	    	
	    	//更新/保存订单费用表
	    	Integer result = xiyiOrderService.saveOrUpdateOrderFee(shOrders.getId(), orderLaundryFeeList);
	        if(result.equals(-1)) {
	        	response.setMobileCodeObj(MobileCodeEnum.ORDERS_REL_FEE);
				return;
	        }
	        //扩展结束
	        response.setData(shOrders.getId());
	    	response.setMobileCodeObj(MobileCodeEnum.COMMON_SUCCESS);
	    	//response.setMobileCodeObj(MobileCodeEnum.ORDERS_ADD_FAIL);
		} catch (Exception e) {
			e.printStackTrace();
			response.setMobileCodeObj(MobileCodeEnum.SYSTEM_ERROR);
		}
	}
	
	
	/**
	 * 得到指定人员的订单信息列表
	 * @author shazhichao
	 * @param request
	 * @param response
	 * 
	 */
	public void getOrderList(MobileOrdersRequest request,MobileResponse<List<ShOrders>> response) {
		if(request.getAccount() == null || request.getAccountId() == null) {
			response.setMobileCodeObj(MobileCodeEnum.ORDERS_NOT_SRCACCOUNT);//下单人id
			return;
		} 
		PageHelper page = new PageHelper();
		request.getPageSize();
		page.setPage(request.getPage());
		page.setRows(request.getPageSize());
		try {
			ShOrders shOrders = new ShOrders();
			if(request.getStatus() != null) {//请求参数的status表示1：已完成、2未完成、3全部订单； 
				if(request.getStatus().equals(1)) {//查询1：已完成的--(所有订单状态为2 的  就是【已完成】)，
					shOrders.setStatus(2);
				}else if(request.getStatus().equals(2)) {//查询2:未完成订单--(除了3关闭和4删除 就是【未完成】)
					shOrders.addQueryData("notStatus", new Integer[]{2,3,4});
				}
				else if(request.getStatus().equals(3)) {//查询3:所有订单--(除了4:删除的)
					shOrders.addQueryData("notStatus", new Integer[]{4});
				}
			}else {
				shOrders.addQueryData("notStatus", new Integer[]{4});
			}
			if(request.getOrderType()!=null){
				shOrders.setOrderType(Integer.valueOf(request.getOrderType().toString()));
			}
			shOrders.setAccount_id(request.getAccountId().toString());
			shOrders.setResidenceId(request.getAccount().getResidenceId());
			
			page.setSort("id");
			page.setOrder("desc");
			DataGrid dataGrid=sendCourierService.dataGrid(shOrders,page);
			response.setData(dataGrid.getRows());
			
		} catch (Exception e) {
			e.printStackTrace();
			response.setMobileCodeObj(MobileCodeEnum.SYSTEM_ERROR);
		} 
	}
	
	
	/**
	 * 得到订单详细
	 * @author shazhichao
	 * @param request
	 * @param response
	 */
	public void getOrderDetail(MobileOrdersRequest request,MobileResponse<ShOrders> response) {
		if(request.getAccount() == null || request.getAccountId() == null) {
			response.setMobileCodeObj(MobileCodeEnum.ORDERS_NOT_SRCACCOUNT);//下单人id
			return;
		}
		if(request.getId() == null ) {
			response.setMobileCodeObj(MobileCodeEnum.ORDERS_ID);
			return;
		}
		try {
			ShOrders shOrders =sendCourierService.getDetailById(request.getId());
			if(shOrders != null) {
				shOrders.setOrderLaundryFeeList(xiyiOrderService.getOrderFeeList(shOrders.getId()));
			}
			response.setData(shOrders);	
		} catch (Exception e) {
			e.printStackTrace();
			response.setMobileCodeObj(MobileCodeEnum.SYSTEM_ERROR);
		}
	}
	
	/**
	 * 
	* @Title: getHistoryAccountInfo
	* @Description: 通过用户id和手机号获取历史用户信息
	* @param request
	* @param response 
	* void  
	* @throws
	 */
	public void getHistoryAccountInfo(MobileOrdersRequest request,MobileResponse<ShHistoryAccount> response) {
		if(request.getAccount() == null || request.getAccountId() == null) {
			response.setMobileCodeObj(MobileCodeEnum.ORDERS_NOT_SRCACCOUNT);//下单人id
			return;
		}
		if(StringUtils.isBlank(request.getDesAccountMobile())) {
			response.setMobileCodeObj(MobileCodeEnum.ORDERS_NOT_DESACCOUNT_MOBILE);
			return;
		}
		ShHistoryAccount shHistoryAccount = new ShHistoryAccount();
		shHistoryAccount.setMobile(request.getDesAccountMobile());
		shHistoryAccount.setAccountId(request.getAccountId());
		try {
			response.setData(sendCourierService.getHistoryAccountInfo(shHistoryAccount));
		}catch(Exception e) {
			e.printStackTrace();
			response.setMobileCodeObj(MobileCodeEnum.SYSTEM_ERROR);
		}
	}
	
	/**
	 * 
	* @Title: getExpressTotalFee 
	* @Description: 获取快递总费用
	* @param request
	* @param response
	* void
	* @throws 
	* @author cyj
	 */
	public void getExpressTotalFee(MobileOrdersRequest request,MobileResponse<Long> response) {
		if(request.getAccount() == null || request.getAccountId() == null) {
			response.setMobileCodeObj(MobileCodeEnum.ORDERS_NOT_SRCACCOUNT);//下单人id
			return;
		}
		if(request.getCompanyId() == null) {
			response.setMobileCodeObj(MobileCodeEnum.ORDERS_NOT_COURIERCOMPANY);
			return;
		}
		if(request.getDesProvinceId() == null) {
			response.setMobileCodeObj(MobileCodeEnum.ORDERS_NOT_DESACCOUNT_AREA_ID);
			return;
		}
		if(request.getWeight() == null) {
			response.setMobileCodeObj(MobileCodeEnum.ORDERS_NOT_WEIGHT);
			return;
		}
		
		ShOrders shOrders = new ShOrders();
		shOrders.setCompanyId(request.getCompanyId());
		shOrders.setDesProvinceId(request.getDesProvinceId());
		shOrders.setWeight(request.getWeight());
		try {
			response.setData(sendCourierService.getExpressTotalFee(shOrders));
		}catch(Exception e) {
			e.printStackTrace();
			response.setMobileCodeObj(MobileCodeEnum.SYSTEM_ERROR);
		}
	}
	
	/**
	 * 
	* @Title: getSrcAreaDetailList
	* @Description: 获取用户取件历史地址列表
	* @param request
	* @param response 
	* void  
	* @throws
	 */
	public void getSrcAreaDetailList(MobileOrdersRequest request,MobileResponse<List<ShSrcAreaDetail>> response) {
		if(request.getAccount() == null || request.getAccountId() == null) {
			response.setMobileCodeObj(MobileCodeEnum.ORDERS_NOT_SRCACCOUNT);//下单人id
			return;
		}
		if(request.getAccount().getResidenceId() == null) {
			response.setMobileCodeObj(MobileCodeEnum.ORDERS_NOT_RESIDENCE);//下单人所属小区id
			return;
		}
		ShSrcAreaDetail srcAreaDetail = new ShSrcAreaDetail();
		srcAreaDetail.setAccountId(request.getAccountId());
		srcAreaDetail.setResidenceId(request.getAccount().getResidenceId());
		try {
			response.setData(srcAreaDetailService.getlList(srcAreaDetail));
		}catch(Exception e) {
			e.printStackTrace();
			response.setMobileCodeObj(MobileCodeEnum.SYSTEM_ERROR);
		}
	}
	
	/**
	 * 
	* @Title: addSrcAreaDetail
	* @Description: 添加用户历史取件地址
	* @param request
	* @param response 
	* void  
	* @throws
	 */
	public void addSrcAreaDetail(MobileOrdersRequest request,MobileResponse<?> response) {
		if(request.getAccount() == null || request.getAccountId() == null) {
			response.setMobileCodeObj(MobileCodeEnum.ORDERS_NOT_SRCACCOUNT);//下单人id
			return;
		}
		if(request.getAccount().getResidenceId() == null) {
			response.setMobileCodeObj(MobileCodeEnum.ORDERS_NOT_RESIDENCE);//下单人所属小区id
			return;
		}
		if(StringUtils.isBlank(request.getSrcAccountAreaDetail())) {
			response.setMobileCodeObj(MobileCodeEnum.ORDERS_NOT_SRCACCOUNT_AREA_DETAIL);
			return;
		}
		ShSrcAreaDetail srcAreaDetail = new ShSrcAreaDetail();
		srcAreaDetail.setAccountId(request.getAccountId());
		srcAreaDetail.setResidenceId(request.getAccount().getResidenceId());
		srcAreaDetail.setAreaDetail(request.getSrcAccountAreaDetail());
		Date now = new Date();
		srcAreaDetail.setGmtCreate(now);
		srcAreaDetail.setGmtModify(now);
		try {
			Integer result = srcAreaDetailService.add(srcAreaDetail);
			if(result == 1) {
				response.setMobileCodeObj(MobileCodeEnum.COMMON_SUCCESS);
			}else {
				response.setMobileCodeObj(MobileCodeEnum.SRC_AREA_DETAIL_ADD);
			}
		}catch(Exception e) {
			e.printStackTrace();
			response.setMobileCodeObj(MobileCodeEnum.SYSTEM_ERROR);
		}
	}
	
	/**
	 * 
	* @Title: deleteSrcAreaDetail
	* @Description: 删除用户历史取件地址
	* @param request
	* @param response 
	* void  
	* @throws
	 */
	public void deleteSrcAreaDetail(MobileOrdersRequest request,MobileResponse<?> response) {
		if(request.getAccountId() == null) {
			response.setMobileCodeObj(MobileCodeEnum.ORDERS_NOT_SRCACCOUNT);//下单人id
			return;
		}
		if(request.getId() == null) {
			response.setMobileCodeObj(MobileCodeEnum.SRC_AREA_DETAIL_ID);
			return;
		}
		try{
			Integer result = srcAreaDetailService.delete(request.getId());
			if(result == 1) {
				response.setMobileCodeObj(MobileCodeEnum.COMMON_SUCCESS);
			}else {
				response.setMobileCodeObj(MobileCodeEnum.SRC_AREA_DETAIL_DELETE);
			}
		}catch(Exception e) {
			e.printStackTrace();
			response.setMobileCodeObj(MobileCodeEnum.SYSTEM_ERROR);
		}
	}
	
}
